﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace LPP.Core.WeChat
{
    public static class WeChatHelper
    {
        public static string GenerateSign(SortedDictionary<string, string> parameters, string apiKey)
        {
            var stringA = string.Join("&", parameters.Where(p => !string.IsNullOrEmpty(p.Value))
                                                      .Select(p => $"{p.Key}={p.Value}"));
            var stringSignTemp = $"{stringA}&key={apiKey}";
            return MD5(stringSignTemp).ToUpper();
        }

        public static bool VerifySign(SortedDictionary<string, string> parameters, string apiKey)
        {
            string sign = parameters["sign"];
            parameters.Remove("sign");
            return sign == GenerateSign(parameters, apiKey);
        }

        public static string ToXml(SortedDictionary<string, string> parameters)
        {
            var sb = new StringBuilder("<xml>");
            foreach (var param in parameters)
            {
                sb.Append($"<{param.Key}>{param.Value}</{param.Key}>");
            }
            sb.Append("</xml>");
            return sb.ToString();
        }

        public static SortedDictionary<string, string> FromXml(string xml)
        {
            var doc = new XmlDocument();
            doc.LoadXml(xml);
            var root = doc.DocumentElement;

            var result = new SortedDictionary<string, string>();
            foreach (XmlNode node in root.ChildNodes)
            {
                result[node.Name] = node.InnerText;
            }

            return result;
        }

        private static string MD5(string input)
        {
            using var md5 = System.Security.Cryptography.MD5.Create();
            var bytes = Encoding.UTF8.GetBytes(input);
            var hash = md5.ComputeHash(bytes);
            return string.Join("", hash.Select(b => b.ToString("x2")));
        }
    }

}
